<script setup>
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import {
  addStorageDevice,
  updateStorageDevice,
} from '@/api/manager/dataManage/deviceManage.js'

defineOptions({
  name: 'StorageAdd',
})

const props = defineProps({
  detail: {
    type: Object,
    default: () => {},
  },
  parkList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['close'])

const loading = ref(false)

const formRef = ref()

const dialogVisible = ref(false)

const title = ref('')

const type = ref('add')

const currentDetail = ref({})

const formRules = ref({
  nickName: [
    {
      message: '设备名称不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  ip: [
    {
      message: 'ip不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  port: [
    {
      message: '端口不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  userName: [
    {
      message: '用户名不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  password: [
    {
      message: '密码不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
})

const handleCancel = () => {
  handleClose()
}

const handleSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      if (type.value === 'add') {
        addStorageDevice(currentDetail.value)
          .then((res) => {
            if (res.success) {
              ElMessage.success('新增成功')
              handleClose(true)
            } else {
              console.error('新增失败', res)
              ElMessage.error(res.message || '新增失败')
            }
          })
          .catch((err) => {
            console.error('新增失败', err)
            ElMessage.error('新增失败')
          })
          .finally(() => {
            loading.value = false
          })
      } else {
        updateStorageDevice({
          pkid: currentDetail.value.pkid,
          nickName: currentDetail.value.nickName,
          ip: currentDetail.value.ip,
          port: currentDetail.value.port,
          userName: currentDetail.value.userName,
          password: currentDetail.value.password,
        })
          .then((res) => {
            if (res.success) {
              ElMessage.success('编辑成功')
              handleClose(true)
            } else {
              console.error('编辑失败', res)
              ElMessage.error(res.message || '编辑失败')
            }
          })
          .catch((err) => {
            console.error('编辑失败', err)
            ElMessage.error('编辑失败')
          })
          .finally(() => {
            loading.value = false
          })
      }
    }
  })
}

const handleClose = (shouldRefresh) => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  emit('close', shouldRefresh)
}

watch(
  () => props.detail,
  (val) => {
    currentDetail.value = val
  },
)

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      formRef.value?.resetFields()
    }
  },
)

defineExpose({ dialogVisible, title, type })
</script>

<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    :title="title"
    width="813px"
    @close="handleClose"
  >
    <div class="custom-detail">
      <el-form
        ref="formRef"
        :model="currentDetail"
        :rules="formRules"
        label-position="right"
        label-width="110"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备名称：" prop="nickName">
              <el-input v-model="currentDetail.nickName" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ip：" prop="ip">
              <el-input v-model="currentDetail.ip" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="端口：" prop="port">
              <el-input v-model="currentDetail.port" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名：" prop="userName">
              <el-input v-model="currentDetail.userName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码：" prop="password">
              <el-input
                v-model="currentDetail.password"
                placeholder="请输入"
                type="password"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-row style="width: 100%" justify="end" align="middle">
        <el-button :loading="loading" @click="handleCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSave"
          >保存</el-button
        >
      </el-row>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form-item {
  width: 100%;
  margin-bottom: 0;
}
</style>
